<?php
function generate_reportid($conn, $length = 10)
{
    $letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $id = '';
    $id .= $letters[rand(0, strlen($letters) - 1)];
    $length -= 1;
    do {
        $id = '';
        for ($i = 0; $i < $length; $i++) {
            $id .= $characters[rand(0, strlen($characters) - 1)];
        }
        $result = $conn->query("SELECT 1 FROM report WHERE id = '$id'");
        if ($result !== false && $result->num_rows > 0) {
            $id = '';
        } else {
            break;
        }
    } while ($id === '');
    return $id;
}
require($_SERVER['DOCUMENT_ROOT'] . '/setting.php');
function verifyToken($token)
{
    global $redis_pz;
    $redis = new Redis();
    $redis->connect($redis_pz['host'], $redis_pz['port']);
    $redis->auth($redis_pz['password']);
    $data = $redis->get($token);
    if ($data) {
        $data = json_decode($data, true);
        if ($data['timestamp'] > time()) {
            return true;
        }
    }
    return false;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'error: requests are not allowed']);
    exit;
}
require($_SERVER['DOCUMENT_ROOT'] . '/cofd/functions.php');
$data_y = file_get_contents("php://input");
$data_x = json_decode($data_y, true);
$token  = $data_x['token'];
if ($token != '') {
    $token  = encrypt($token, 'D', 'yhsdylpo9342');
} else {
    echo json_encode(['success' => false, 'message' => 'error: invalid token']);
    exit;
}
if (!verifyToken($token)) {
    echo json_encode(['success' => false, 'message' => 'error: invalid token']);
    exit;
}
require($_SERVER['DOCUMENT_ROOT'] . '/cofd/common.php');
$userid = $data_x['userid'];
$timenow = date('Y-m-d H:i:s');
$beuserid = encrypt($data_x['beuserid'],'D','yhsdylpo9342');
$file_name = $data_x['file_name'];
$fileid = encrypt($data_x['file_ids'],'D','yhsdylpo9342');
$reason = $data_x['reason'];
$reportid = generate_reportid($conn);
$sql = "INSERT INTO `report` (`id`,`fileid`,`reason`,`filename`,`timei`,`userid`,`beuserid`) VALUES (?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sssssss", $reportid, $fileid, $reason, $file_name, $timenow, $userid, $beuserid);
if($stmt->execute()){
    echo json_encode(['success' => true, 'message' => 'report has been sent']);
}else{
    echo json_encode(['success' => false, 'message' => 'error: report could not be sent']);
}
$stmt->close();
$conn->close();